import React from "react";
import AMapLoader from "@amap/amap-jsapi-loader";
import { useEffect } from "react";
import { Button } from "antd";
export default function Area() {
  let map = {}; //地图实例对象
  var polyEditor = {};
  useEffect(() => {
    AMapLoader.load({
      key: "326929be57e60ab4ae208dfbbf54063d", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ["AMap.PolygonEditor"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
      .then((AMap) => {
        map = new AMap.Map("container", {
          //设置地图容器id
          viewMode: "3D", //是否为3D地图模式
          zoom: 10, //初始化地图级别
          center: [106.55, 29.57], //初始化地图中心点位置
        });
        mapDraw(AMap);
      })
      .catch((e) => {
        console.log(e);
      });
  }, []);

  let mapDraw = (AMap) => {
    var path1 = [  //矢量图坐标数据集
      [116.475334, 39.997534],
      [116.476627, 39.998315],
      [116.478603, 39.99879],
      [116.478529, 40.000296],
      [116.475082, 40.000151],
      [116.473421, 39.998717],
    ];
    var path2 = [
      [116.474595, 40.001321],
      [116.473526, 39.999865],
      [116.476284, 40.000917],
    ];
    var polygon1 = new AMap.Polygon({ //创建矢量图对象
      path: path1,
    });
    var polygon2 = new AMap.Polygon({
      path: path2,
    });

    map.add([polygon1, polygon2]); //向地图对象绘制矢量图形
    map.setFitView();  //地图视图自动跳转到有矢量图的位置
    polyEditor = new AMap.PolygonEditor(map);
    polyEditor.addAdsorbPolygons([polygon1, polygon2]);  //编辑矢量图
    polyEditor.on("add", function (data) {
      console.log(data);
      var polygon = data.target;
      polyEditor.addAdsorbPolygons(polygon);
      polygon.on("dblclick", () => {
        polyEditor.setTarget(polygon);
        polyEditor.open();
      });
    });
    polygon1.on("dblclick", () => { //为矢量图对象绑定双击事件
      polyEditor.setTarget(polygon1);
      polyEditor.open();
    });
    polygon2.on("dblclick", () => {
      polyEditor.setTarget(polygon2);
      polyEditor.open();
    });

    // polyEditor.setTarget(polygon2);
    // polyEditor.open();
  };

  function createPolygon() {
    polyEditor.close();
    polyEditor.setTarget();
    polyEditor.open();
  }
  return (
    <div>
      <Button type="primary" onClick={createPolygon}>
        新建范围
      </Button>
      <Button onClick={createPolygon}>确认范围</Button>
      <div
        id="container"
        style={{ height: "500px", border: "1px solid red" }}
      ></div>
    </div>
  );
}
